<?php

namespace app\admin\controller;

use app\admin\model\RoomModel;
use app\admin\model\ReasonModel;
use app\admin\model\SchoolModel;
use app\admin\model\StudentModel;
use app\admin\model\ScoreModel;
use think\Db;
use think\db\Query;
use cmf\controller\AdminBaseController;
use app\admin\model\RecordModel;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class RecordController extends AdminBaseController
{
    private $accessKey ="XigVF1dc-sl0niWZBW6P7T0IkeDd9_ntlvxPf3yR"; // 你的 AccessKey
    private $secretKey = "5ykt5QslkUo3h5laEOegCNIO87WcestNnUTUBBDt"; // 你的 SecretKey
    private $bucket = "app-zhang"; // 你在七牛云创建的空间名称

    //积分记录列表
    public function index()
    {
        $name=$this->request->param('name');
        $record=Db::name('record')
            ->join('jf_student','student_id = jf_student.id','LEFT')
            ->join('jf_reason','reason_id = jf_reason.id')
            ->join('jf_score','score_id = jf_score.id')
            ->field('jf_record.*')
            ->field('jf_student.name as student_name,jf_reason.name as reason_name,jf_score.name as score_name')
            ->where(function(Query $query) use ($name){
                if($name){
                    $query->where('jf_student.name','like',"%$name%");
                }
            })
            ->order("id DESC")
            ->paginate(3, false, ['query' => request()->param()]);
        //分页样式
        $page=$record->render();
        //映射页面
        return view('',['record'=>$record,'page'=>$page]);
    }

    //添加记录页面
    public function add()
    {
        $school = SchoolModel::select();
        $score = ScoreModel::select();
        $reason = ReasonModel::select();
        return view('',['school' => $school, 'score' => $score, 'reason' => $reason]);
    }
    //添加记录提交
    public function addPost()
    {
        //判断提交类型
        if ($this->request->isPost()){
            //获取提交数据
            $data=input();
            unset($data['photo_name']);
            $data['create_time'] = date('Y-m-d H:i:s',time());
            $add=RecordModel::create($data);

            //判断
            if ($add){
                $this->success('添加成功!','record/index');
            }else{
                $this->error('添加失败!');
            }

        }
    }
    //编辑记录页面
    public function edit()
    {
        $id = input('id');
        $record = RecordModel::get($id);

        $school = SchoolModel::all();
        $reason = ReasonModel::all();
        $score = ScoreModel::all();

        // 该学生属于哪个班级
        $room_id = StudentModel::where('id', $record->student_id)->value('room_id');
        // 该班级属于哪个学校
        $school_id = RoomModel::where('id', $room_id)->value('school_id');
        // 当前学校下的班级
        $room = RoomModel::where('school_id', $school_id)->select();
        // 当前班级下的学生
        $student = StudentModel::where('room_id', $room_id)->select();

        return $this->fetch('', [
            'record' => $record,
            'school' => $school,
            'reason' => $reason,
            'score' => $score,
            'room_id' => $room_id,
            'school_id' => $school_id,
            'room' => $room,
            'student' => $student
        ]);
    }
    public function editPost()
    {
        $data = input();
        $edit=RecordModel::update($data,['id'=>$data['id']]);
        if ($edit) {
            $this->success("修改成功！", "record/index");
        }else{
            $this->error("修改失败！");
        }
    }
    //根据学校id查询该学校下所有班级
    public function getRoomBySchool()
    {
        $schoolId=input('school_id');
        $rooms=RoomModel::where('school_id',$schoolId)->select();
        if ($rooms){
            $options=["<option value=''>请选择班级</option>"];
            foreach ($rooms as $v){
                $opt="<option value='".$v->id."'>".$v->name."</option>";
                array_push($options,$opt);
            }
            return $options;
        }else{
            return "<option value=''>暂无数据</option>";
        }
    }
    //根据班级id查询该班级下所有学生
    public function getStudentByRoom()
    {
        $roomId = input('room_id');
        $student = StudentModel::where('room_id',$roomId)->select();
        if ($student){
            $options=["<option value=''>请选择学生</option>"];
            foreach ($student as $v){
                $opt = "<option value='".$v->id."'>".$v->name."</option>";
                array_push($options,$opt);
            }
            return $options;
        }else{
            return"<option value=''>暂无数据</option>";
        }
    }

    //删除
    public function delete()
    {
        $id=input('id');
        $del=RecordModel::destroy($id);
        //$data=input();
        //$del=RecordController::destroy($data['id']);
        if ($del){
            $this->success('删除成功!',"record/index");
        }else{
            $this->error('删除失败!');
        }
    }

    public function upload(){
        $file = $_FILES['picture'];
        // 截取后缀名
        $ext = strchr($file['name'], '.');
        // 构建鉴权对象
        $auth = new Auth($this->accessKey, $this->secretKey);
        // 生成上传 Token
        $token = $auth->uploadToken($this->bucket);
        // 要上传文件的本地路径
        $filePath = $file['tmp_name'];
        // 上传到七牛后保存的文件名
        $key = time().uniqid().$ext;
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            return json(['code' => 100,'msg' =>'上传失败']); // 失败
        } else {
            return json(['code' => 200,'msg' =>'上传成功','path' => 'http://qiniu.zhangjiwei.top/'.$key]); // 成功，$key 就是在七牛云的文件名，加上你在七牛云的外链地址就可以访问到文件
        }
    }
}